using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity;
using Admin.NET.Application.Service.Report.Dto;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;

namespace Admin.NET.Application.Service.Report;

/// <summary>
/// 房间树结构
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class RoonTreeService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<Building> _rep;

	public RoonTreeService(SqlSugarRepository<Building> rep)
	{
		_rep = rep;
	}

	[HttpGet("/reporttree/init")]
	public async Task<RoomInfoTree> ReportTree()
	{
		RoomInfoTree roomInfoTree = new RoomInfoTree();
		List<RoomTree> buildings = await (from u in _rep.AsQueryable()
			select new RoomTree
			{
				Id = u.Id,
				Icon = "<el-icon><Discount /></el-icon>",
				Name = u.Name,
				Type = 0
			}).ToListAsync();
		List<long> listId = buildings.Select((RoomTree u) => u.Id).ToList();
		if (listId.Count > 0)
		{
			List<RoomTree> roomInfo = await (from u in _rep.Context.Queryable<Room>()
				where u.BuildingId != 0
				select new RoomTree
				{
					BuildingId = u.BuildingId,
					Id = u.Id,
					Name = u.Name,
					Type = 1
				}).ToListAsync();
			List<RoomTree> roomInfoMeter = await (from u in _rep.Context.Queryable<ElectricMeter>()
				where u.RoomId != null
				select new RoomTree
				{
					BuildingId = u.RoomId.Value,
					Id = u.Id,
					Name = u.Name,
					Type = 2
				}).ToListAsync();
			roomInfo.ForEach(delegate(RoomTree u)
			{
				u.Children = roomInfoMeter.Where((RoomTree s) => s.BuildingId == u.Id).ToList();
			});
			buildings.ForEach(delegate(RoomTree u)
			{
				u.Children = roomInfo.Where((RoomTree s) => s.BuildingId == u.Id).ToList();
			});
			bool sucess = false;
			for (int i = 0; i < buildings.Count; i++)
			{
				for (int j = 0; j < buildings[i].Children.Count; j++)
				{
					if (buildings[i].Children[j].Children.Count > 0)
					{
						roomInfoTree.Checked = buildings[i].Children[j].Children.FirstOrDefault();
						sucess = true;
						break;
					}
				}
				if (sucess)
				{
					break;
				}
			}
		}
		List<RoomTree> notroommeters = await (from u in _rep.Context.Queryable<ElectricMeter>()
			where u.RoomId == null
			select new RoomTree
			{
				BuildingId = u.RoomId.Value,
				Id = u.Id,
				Name = u.Name,
				Type = 2
			}).ToListAsync();
		if (notroommeters.Count > 0)
		{
			buildings.AddRange(notroommeters);
		}
		roomInfoTree.RoomTrees = buildings;
		return roomInfoTree;
	}
}
